package com.tbit.uqbike.service.business.tag.strategy.add;

import cn.hutool.core.collection.CollectionUtil;
import com.tbit.uqbike.enums.TagOperationType;
import com.tbit.uqbike.object.business.UserInfo;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.tag.MachineTag;
import com.tbit.uqbike.object.pojo.vo.BatchOperationMsgVO;
import com.tbit.uqbike.service.base.MachineService;
import com.tbit.uqbike.webmanager.dto.TagBindDTO;
import com.tbit.uqbike.webmanager.resp.tag.TagResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Set;


/**
 * 通过设备ID machineId 添加标签
 *
 *
 * @author <a href="mailto:chen.chaoxiong@tbit.com.cn">ChenChaoXiong</a>
 * @since 2024/7/12
 */
@Component
public class AddByMachineIdStrategy extends AbstractAddTagOperation {
    @Autowired
    private MachineService machineService;

    @Override
    protected BatchOperationMsgVO<TagResult> addTag(TagBindDTO tagBind) {

        Integer brandId = tagBind.getBrandId();
        Integer accountId = tagBind.getAccountId();
        UserInfo userInfo = tagBind.getUserInfo();

        if (CollectionUtil.isEmpty(tagBind.getMachineIds()) || CollectionUtil.isEmpty(tagBind.getTagIds())) {
            return BatchOperationMsgVO.empty();
        }

        Set<Integer> machineIds = tagBind.getMachineIds();
        Set<Long> tagIds = tagBind.getTagIds();


        //校验设备是否存在
        List<Machine> machineList = machineService.getByIds(machineIds);
        if (CollectionUtil.isEmpty(machineList)) {
            return BatchOperationMsgVO.empty();
        }

        BatchOperationMsgVO<TagResult> results = new BatchOperationMsgVO<>();
        if (!validateAndFilterTags(tagIds, brandId, accountId, results) || !validateAndFilterMachines(machineIds, brandId, accountId, results)) {
            return results;
        }

        List<MachineTag> addableMachineTags = caculateAddableMachineTags(machineIds, tagIds, brandId, accountId, userInfo,results);
        saveMachineTags(addableMachineTags,results);
        return results;
    }

    @Override
    public TagOperationType getOperationType() {
        return TagOperationType.ADD_BY_MACHINE_ID;
    }
}
